package com.future.bs.engine;

import com.future.bs.component.business.Business;
import com.future.bs.component.report.Report;
import com.future.bs.context.BusinessStatus;
import com.future.bs.context.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 * 业务流引擎默认实现
 * </p>
 *
 * @author Jingjie
 * @since 2020-11-07 21:24
 */
public class DefaultBusinessEngine<T extends Context> implements BusinessEngine<T> {
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultBusinessEngine.class);

    @Override
    public Report<T> execute(Business<T> businessStream, T context) {
        LOGGER.info("Start to execute business stream.");
        Report<T> report;
        try {
            report = businessStream.execute(context);
        } catch (Exception e) {
            // 向后回滚
            String message = "Execute business occur error, start to rollback executed businesses.";
            LOGGER.error(message, e);
            businessStream.rollback(context);
            throw new RuntimeException(message, e);
        }
        if (report == null || report.getStatus() != BusinessStatus.SUCCESS) {
            // 向后回滚
            LOGGER.warn("Execute business failed, start to rollback executed businesses.");
            businessStream.rollback(context);
        }
        return report;
    }
}